<template>
  <div class="chat-item">
    <!-- 用户提问内容 -->
    <div class="chat-list" v-for="message in AI_OutList" :key="message.id">
      <div :class="['chat-dialog', message.role === 'user' ? 'user-message' : 'ai-message']">
        <template v-if="message.role === 'user'">
          {{ message.content }}
        </template>
        <template v-else>
          <mavonEditor
            class="content-show"
            :toolbarsFlag="false"
            :subfield="false"
            defaultOpen="preview"
            :ishljs="true"
            v-model="message.content"
            ref="md"
          />
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import MarkdownIt from "markdown-it";
import katex from "markdown-it-katex";
import 'katex/dist/katex.min.css';



export default {
  name: "ChatDialogComponents",
  components: {
    mavonEditor,
  },
  props: {
    AI_OutList: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {      
      markdownContent: this.content ? this.content : "```console```",
      renderedMarkdown: '', //格式化后的内容
      md: null,
    };
  },
  computed: {
    computedAIOutList() {
      return this.AI_OutList.map(message => ({
        role: message.role,
        formattedContent: this.renderMarkdown(message.content)
      }));
    }
  },
  mounted() {
    // 初始化 MarkdownIt 实例并使用 katex 插件
    this.md = new MarkdownIt();
    this.md.use(katex);
    // console.log(this.content)
  },
  methods: {
    // 使用md加载内容
    renderMarkdown(txt) {
      // const modifiedOutput = txt.replace(/\\\[/g, '[').replace(/\\\]/g, ']');
      return this.md.render(txt);
    }, 
  }, 
  watch: {    
    AI_OutList: {
      handler(newValue) {
        if (newValue) {
          this.AI_OutList = newValue;
        }
      },
      immediate: true,
    },
  },
};
</script>
<style scoped>
.chat-item {
  width: 100%;
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
}



::v-deep .v-note-wrapper {
  min-height: 60px;
}

.chat-list {
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  align-items: flex-end; /* 让聊天项靠右对齐 */
  width: 100%;
}

.user-message {
  display: flex;
  justify-content: flex-end; /* 保持靠右 */
  max-width: 60%; /* 限制最大宽度为60% */
  min-width: 0; /* 允许内容宽度小于容器宽度 */
  padding: 8px;
  border-radius: 6px;
  background-color: #3d65f7;
  color: #ffffff;
  margin-bottom: 10px;
  word-wrap: break-word; /* 允许内容在达到最大宽度时换行 */
  overflow-wrap: break-word; /* 允许在长单词或URL内部进行换行 */
}

.ai-message {
  width: 100%;
  background-color: #f0f0f0;
  padding: 3px;
  border-radius: 6px;
  margin-bottom: 10px;
  word-wrap: break-word; /* 允许内容在达到最大宽度时换行 */
  overflow-wrap: break-word; /* 允许在长单词或URL内部进行换行 */
  align-self: flex-start; /* 让AI消息靠左对齐 */
}
</style>